package com.weishaoying.example.base.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author WeiShaoying
 * @date 2018/4/3
 */
@Aspect
@Component //不能省略
public class LogAspect {

    //1.通过注解拦截
    //定义切点：使用了@Action注解的地方
    @Pointcut("@annotation(com.weishaoying.example.base.aop.Action)")
    public void pointCut4Action() {
    }

    @After("pointCut4Action()")
    public void after(JoinPoint jointPoint) {
        MethodSignature signature = (MethodSignature) jointPoint.getSignature();
        Method method = signature.getMethod();
        //通过方法获得注解
        Action action = method.getAnnotation(Action.class);
        System.out.println("注解拦截：" + action.name());
    }

    //2.通过表达式拦截DogService的所有方法
    @Before("execution(* com.weishaoying.example.base.aop.DogService.*(..))")
    public void before(JoinPoint joinpoint) {
        MethodSignature signature = (MethodSignature) joinpoint.getSignature();
        Method method = signature.getMethod();
        String methodName = method.getName();
        int count = method.getParameterCount();
        System.out.println(methodName + "有" + count + "个参数");
    }
}
